import { token } from "./token";

const BASE_URL = "http://192.168.1.107:50000";

// 请求参数定义类型
interface Params {
  url: string;
  data?: {};
  method?: "GET" | "POST" | "DELETE" | "PUT";
  success?: (data: any) => void;
  fail?: (err: any) => void;
  complete?: () => void;
}

// 请求函数
export const request = ({
  url,
  data = {},
  method = "GET",
  success,
  fail,
  complete,
}: Params) => {
  let header: any = {};
  header["Authorization"] = "Bearer " + token;
  // 判断是不是有网络
  // if(){}

  // 如果有网络
  wx.request({
    url: BASE_URL + url,
    data,
    header,
    method,
    success(res: any) {
      // console.log(res.data);
      success && success(res.data);
    },
    fail(err) {
      console.log(err);
      fail && fail(err);
    },
    complete() {
      // console.log("执行完毕");
      complete && complete();
    },
  });
};

// 将请求函数 Promise 化

export const http = (params: Params) => {
  return new Promise((resolve, reject) =>
    request({
      ...params,
      success({ data, code }) {
        // console.log(data,code);
        if (code === 204 || data) {
          resolve(data);
        }
      },
      fail(err) {
        reject(err);
      },
    })
  );
};
